<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" width="85vw" align-center style="z-index: 1000;" destroy-on-close @closed="$emit('closed')" :close-on-click-modal="false" fullscreen>
        <div class="widgets-content">
            <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="150px" label-position="top">
                <el-card class="box-card">
                    <el-row :gutter="1">
                        <el-col :span="24">
                            <div class="titleBox titleBox1">
                                基本信息
                            </div>
                        </el-col>
                    </el-row>
                    <el-row :gutter="1">
                        <el-col :span="4">
                            <el-form-item label="关联项目" prop="project_id">
                                <el-input v-model="project_code" placeholder="请选择项目" readonly @click="checkItem"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="任务类型" prop="task_type">
                                <el-select v-model="form.task_type" placeholder="请选择任务类型" style="width:100%" clearable filterable @change="taxHeadChange">
                                    <el-option label="布场任务" :value="1"/>
                                    <el-option label="撤场任务" :value="2"/>
                                    <el-option label="临时任务" :value="3"/>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="任务名称" prop="task_name">
                                <el-input v-model="form.task_name" placeholder="请输入任务名称" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="任务负责人" prop="task_staff">
                                <el-input v-model="form.task_staff" placeholder="请输入任务负责人" clearable></el-input>
                                <!-- <el-select v-model="form.task_staff" filterable clearable placeholder="请选择销售" style="width:100%">
                                    <el-option v-for="item in adminList" :key="item.id" :label="item.name" :value="item.id"/>
                                </el-select> -->
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="负责人电话" prop="task_mobile">
                                <el-input v-model="form.task_mobile" placeholder="请输入负责人电话" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="1">
                        <el-col :span="4">
                            <el-form-item label="任务开始日期" prop="start_time">
                                <el-date-picker v-model="form.start_time" type="datetime" placeholder="开始时间" format="YYYY-MM-DD HH:mm:ss" date-format="MMM DD, YYYY" time-format="HH:mm" style="width:100%" :value-format="'YYYY-MM-DD HH:mm:ss'" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="任务结束日期" prop="end_time">
                                <el-date-picker v-model="form.end_time" type="datetime" placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" date-format="MMM DD, YYYY" time-format="HH:mm" style="width:100%" :value-format="'YYYY-MM-DD HH:mm:ss'" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="任务人数" prop="task_user_num">
                                <el-input v-model="form.task_user_num" placeholder="请输入任务人数" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-card>
                <el-card class="box-card">
                    <el-row :gutter="1">
                        <el-col :span="24">
                            <div class="titleBox titleBox1">
                                位置信息
                            </div>
                        </el-col>
                    </el-row>
                    <el-row :gutter="1">
                        <el-col :span="6">
                            <el-form-item label="经度" prop="longitude">
                                <el-input v-model="form.longitude" placeholder="请输入经度" clearable></el-input>
                            </el-form-item>
                            </el-col>
                        <el-col :span="6">
                            <el-form-item label="纬度" prop="latitude">
                                <el-input v-model="form.latitude" placeholder="请输入纬度" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="任务地点" prop="task_address">
                                <el-input v-model="form.task_address" placeholder="请输入任务地点" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="1">
                        <div id="amap-container">
                            <el-input id="tipinput" v-model="searchValue" placeholder="请输入地址" clearable></el-input>
                            <el-row class="address" style="margin-top: 10px;">
                                <!-- 当前地址是： {{ formattedAddress }} -->
                            </el-row>
                            <div id="custom-amap" class="map" tabindex="0"/>
                        </div>
                    </el-row>
                </el-card>
            </el-form>
        </div>
        <el-footer style="text-align: right;position: fixed;bottom: 0;right: 0;left: 0;padding: 10px 20px;background: #fff;border-top: 1px solid #eee;">
            <el-button @click="visible = false">取 消</el-button>
            <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
        </el-footer>
        <item-list v-if="dialog.item" ref="itemDialog" @success="itemBack" @closed="dialog.item=false"></item-list>
  </el-dialog>

</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import itemList from '@/views/project/list/itemList.vue'
export default {
    components: {itemList},
    emits: ['success', 'closed'],
    data() {
        return {
            dialog:{
                item:false
            },
            mode: "add",
            titleMap: {
                add: '新增任务',
                edit: '编辑任务',
                show: '查看'
            },
            visible: false,
            isSaveing: false,
            //表单数据
            form: {
                task_name: "",
                task_address: "",
                task_staff: "",
                task_mobile: "",
                remark: "",
                start_time: this.moment().format('YYYY-MM-DD HH:mm:ss'),
                end_time: "",
                task_user_num: "",
                latitude:"",
                longitude:"",
                project_id:"",
            },
            //验证规则
            rules: {
                project_id: [{required: true, message: '请选择项目'}],
                task_type: [{required: true, message: '请选择任务类型'}],
                task_name: [{required: true, message: '请输入任务名称'}],
                task_staff: [{required: true, message: '请输入任务负责人'}],
                task_mobile: [{required: true, message: '请输入任务负责人电话'}],
                start_time: [{required: true, message: '请选择开始时间'}],
                end_time: [{required: true, message: '请选择结束时间'}],
            },
            map: null,// 地图对象
            formattedAddress: '',
            position: {},// 地址对应的经纬度信息
            searchValue: '',// 检索关键字
            placeSearch: null,// 检索函数对象
            searchInfoList: [],// 检索结果数据数据
            marker: '', // 地图标记
            geocoder: '', // 地址解析（正向）
            name: '',// 地址名称
            adcode: '',
            config: {
                secret: '',
                key: ''
            },
            adminList: [],
            project_code: "",
        }
    },
    mounted() {
        // this.getMapKey()
        this.initMap()
        this.getAdmin()
    },
    beforeUnmount() {
        this.destroyMap()
    },
    watch: {},
    methods: {
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        //表单提交方法
        submit() {
            console.log('this.form :>> ', this.form);
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    var res = [];
                    if (this.form.id) {
                        res = await this.$API.task.task.edit.post(this.form);
                    } else {
                        res = await this.$API.task.task.add.post(this.form);
                    }
                    this.isSaveing = false;
                    if (res.code == 1) {
                        this.$emit('success', this.form, this.mode)
                        this.visible = false;
                        this.$message.success("操作成功")
                    } else {
                        this.$alert(res.message, "提示", {type: 'error'})
                    }
                } else {
                    return false;
                }
            })
        },
        //表单注入数据
        async setData(data) {
            Object.assign(this.form, data)
            this.project_code = data.project && data.project.metting
        },
        async getAdmin(){
            var res = await this.$API.system.admin.all.get();
            this.adminList = res.data
        },
        destroyMap() {
            if (this.map) {
                console.log(123);
                this.map.off("click", this.clickMapHandler)
                this.map.destroy()
                this.map = null;
            }
        },
        //   初始化地图页面
        initMap() {
            window._AMapSecurityConfig = {
                // securityJsCode: this.config.secret,
                // securityJsCode: '45a309721d374f57b1e1e395a7caad97',      //secret    2191
                // securityJsCode: 'c34c0087ae7dc160fcc272f990a003b7',         //secret    2171
                securityJsCode: '5c3150016243a63f1ac852de8b4e0353',         //secret    2171
            }
            this.$nextTick(() => {
                AMapLoader.load({
                    // key: this.config.key,
                    // key: 'e6f34c0a08515427adb55133f85aabc9',             //key   2191
                    // key: 'e4247db8e7fe8b5d3a312703f7c0089f',                //key   2171
                    key: '5a4882715bb7b0d91b9562cc6363dc7f',                //key   2171
                    version: '2.0',
                    plugins: ['AMap.Scale', 'AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Marker', "AMap.Geocoder", 'AMap.Zoom', 'AMap.ToolBar'],
                    AMapUI: {
                        plugins: ['misc/PositionPicker'], // 添加组件
                    },
                }).then((AMap) => {
                    console.log('AMap :>> ', AMap);
                    let lo = 117.121932
                    let lu = 39.111732
                    this.map = new AMap.Map('custom-amap', {
                        viewMode: '3D',
                        zoom: 15,
                        // center: [117.121932, 39.111732],
                        center: [this.form.longitude?this.form.longitude:lo, this.form.latitude?this.form.latitude:lu],
                        // mapStyle: "amap://styles/whitesmoke", //设置地图的显示样式
                    });
                    this.map.addControl(new AMap.Scale())
                    var auto = new AMap.AutoComplete({
                        input: "tipinput"
                    })
                    console.log('auto', auto)
                    this.placeSearch = new AMap.PlaceSearch({
                        map: this.map
                    })
                    console.log('searchValue', this.searchValue)
                    // if (this.searchValue) {
                    //
                    // }
                    this.placeSearch.search(this.searchValue, function (status, result) {
                        console.log(status, result)
                    });
                    auto.on("select", this.selectop)
                    this.placeSearch.on("markerClick", this.clickMarkerHandler)
                    // this.map.on('click', this.clickMapHandler);
                    this.map.on('click', (e) => {
                        console.log('点击' , e);
                        // 清除之前的标记
                        this.map.clearMap();
                        this.form.latitude = e.lnglat.getLat()
                        this.form.longitude = e.lnglat.getLng()
                        var marker = new AMap.Marker({
                        position: new AMap.LngLat(Number(this.form.longitude), Number(this.form.latitude)),   // 经纬度对象，也可以是经纬度构成的一维数组[经度, 纬度]
                        // title: this.$store.state.fromObj.address,
                        // label: {
                        //   content: '<div style="color: blue; font-size: 14px; font-weight: bold; border: none;">标记</div>',
                        //   offset: new AMap.Pixel(0, -30), // 调整标签的偏移量，使其显示在标记的上方
                        // },
                        // icon: new AMap.Icon({
                        //   image: "img/map.png",
                        //   size: new AMap.Size(37, 37), //图标大小
                        //   imageSize: new AMap.Size(37, 37)
                        // })
                        });
                        marker.setMap(this.map);
                    });
                    // 修改地图中心点
                    // this.map.setCenter([117.121932, 39.111732]);
                    // 创建一个 Marker 实例：
                    var marker = new AMap.Marker({
                        position: new AMap.LngLat(Number(this.form.longitude), Number(this.form.latitude)),   // 经纬度对象，也可以是经纬度构成的一维数组[经度, 纬度]
                        // title: this.$store.state.fromObj.address,
                        // label: {
                        //   content: '<div style="color: blue; font-size: 14px; font-weight: bold; border: none;">标记</div>',
                        //   offset: new AMap.Pixel(0, -30), // 调整标签的偏移量，使其显示在标记的上方
                        // },
                        // icon: new AMap.Icon({
                        //   image: "img/map.png",
                        //   size: new AMap.Size(37, 37), //图标大小
                        //   imageSize: new AMap.Size(37, 37)
                        // })
                    });
                    // 将创建的点标记添加到已有的地图实例：
                    this.map.add(marker);
                }).catch(e => {
                    console.log('e :>> ', e);
                });
            })
        },
        selectop(e) {
            console.log(e, 'search')
            this.placeSearch.setCity(e.poi.adcode)
            this.placeSearch.search(e.poi.name) //关键字查询查询
        },
        clickMarkerHandler(e) {
            console.log('address',e)
            this.position = e.data
            this.form.task_address = e.data.address
            console.log('this.position', this.position)
        },
        /**获取地图key*/
        async getMapKey() {
            var res = await this.$API.setting.sys.get_key.get();
            if (res.code == 1) {
                this.config.key = res.data.key
                this.config.secret = res.data.secret
                this.initMap()
            }
        },
        // 添加点击地图的事件处理函数
        clickMapHandler(e) {
            console.log('地图被点击了', e);
            this.form.latitude = e.lnglat.getLat()
            this.form.longitude = e.lnglat.getLng()
        },
        checkItem(){
            this.dialog.item = true
			this.$nextTick(() => {
				this.$refs.itemDialog.open('add')
			})
        },
        itemBack(data){
            this.form.project_id = data.id
            this.project_code = data.metting
        },
    }
}
</script>

<style lang="scss">
#amap-container {
    .el-input__clear {
        line-height: 34px;
        /*top: 20px;*/
    }
    #custom-amap {
        height: 400px;
        width: 1500px;
        margin-top: 10px;
        //border: 1px solid #ccc;
    }
    .input-with {
        /*position: fixed;*/
        /*top: 40px;*/
        z-index: 1;
        width: 580px;
    }
    .address {
        color: #373737;
    }
}
.widgets-content {
  flex: 1;
  padding: 15px 15px;

  .el-form {
    height: 710px;
    overflow: auto;
    overflow-x: hidden;
  }

  .SeletBox {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .el-col {
    margin-right: 22px;
  }

  .el-form-item {
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;

    .el-form-item__label {
      justify-content: flex-start;
    }

    .el-form-item__content {
      width: 100%;
    }
  }

  .box-card {
    margin-bottom: 10px;
  }

  .el-form {
    //background: #ffffff;
    //padding: 20px;
    //min-height: 90%;
    .titleBox {
      font-size: 18px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #333333;
      padding-bottom: 10px;
      border-bottom: 1px solid #E6E6E6;
      margin-bottom: 14px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .titleBox1 {
      font-weight: 600;
      border: none;
      font-size: 16px;
    }
  }
}
</style>
